#include "pool.h"

ThreadPool::ThreadPool(size_t numThreads)
    :m_stop(false)
{
    for (size_t i = 0; i < numThreads; ++i)
    {
        m_workers.emplace_back([this] {
        while (true) {
            std::function<void()> task;
            {
                std::unique_lock<std::mutex> lock(m_queueMutex);
                //会在给定的互斥锁 lock 上等待，直到满足lambda表达式
                m_condition.wait(lock, [this] {
                    return m_stop || !m_tasks.empty();
                });
                if (m_stop && m_tasks.empty())
                {
                    return;
                }
                    task = std::move(m_tasks.front());//将任务取出放入线程中执行
                    m_tasks.pop();
                }
                task();
            }
        });
    }
}
ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(m_queueMutex);//作用域锁，可以随意控制加锁、解锁权限，包括线程转移锁
        m_stop = true;
    }
    m_condition.notify_all();
    for (std::thread& worker : m_workers) {
        worker.join();//阻塞
    }
}

//template<typename Func>
//std::future<typename std::result_of<Func()>::type> ThreadPool::enqueue(Func&& func) {
//    using ReturnType = typename std::result_of<Func()>::type;
//    auto task = std::make_shared<std::packaged_task<ReturnType()>>(std::forward<Func>(func));
//    std::future<ReturnType> result = task->get_future();
//    {
//        std::unique_lock<std::mutex> lock(m_queueMutex);
//        m_tasks.emplace([task]() { (*task)(); });
//    }
//    m_condition.notify_one();
//    return result;
//}